package cn.yhjz.platform.system.config.security;

import cn.yhjz.common.AjaxResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 检测到未登录时，返回前端
 */
@Component
public class CuAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        AjaxResponse res = AjaxResponse.fail(HttpStatus.HTTP_UNAUTHORIZED, "需要登录！");
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
        response.getWriter().write(JSONUtil.toJsonStr(res));
    }
}
